package com.hqq.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * AspectProxy
 * 切面代理类
 * Created by heqianqian on 2017/7/21.
 */
public class AspectProxy implements Proxy {

    private static final Logger LOGGER = LoggerFactory.getLogger(AspectProxy.class);

    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object proxyResult = null;

        Method targetMethod = proxyChain.getTargetMethod();
        Class<?> targetClass = proxyChain.getTargetClass();
        Object[] methodParams = proxyChain.getMethodParams();

        begin();
        try {
            before(targetClass, targetMethod, methodParams);
            proxyResult = proxyChain.doProxyChain();
            after(targetClass, targetMethod, methodParams, proxyResult);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        } finally {
            end();
        }
        return proxyResult;
    }

    /**
     * 代理方法执行前逻辑
     */
    protected void before(Class<?> targetClass, Method targetMethod, Object[] methodParams) {
    }


    /**
     * 代理方法执行后逻辑
     */
    protected void after(Class<?> targetClass, Method targetMethod, Object[] methodParams, Object proxyResult) {
    }

    /**
     * 代理方法出现异常时逻辑
     */
    protected void error(Class<?> targetClass, Method targetMethod, Object[] methodParams, Exception e) {

    }

    protected void begin() {
    }


    protected void end() {
    }

}
